package com.atguigu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {

    public static void main(String[] args) throws IOException {
        // 创建ServerSocketChannel -> SocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 得到一个selector对象
        Selector selector = Selector.open();

        // 设置端口号，在服务端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        // 设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);

        // 把serverSocketChannel注册到selector，监听时间为OP_ACCECPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("注册后的SelectionKey，数量=" + selector.keys().size());

        while (true) {
            // 等待1秒钟，没有事件发生，返回
            if (selector.select(10000) == 0) {
                System.out.println("服务器等待1秒，无连接");
                continue;
            }

            // 如果返回大于0 ，获取SelectionKey集合
            // selector.selectedKeys()返回关注事件的结合
            // 通过selectionKeys反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            System.out.println("有事件响应的selectedKeys，数量=" + selectionKeys.size());


            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey selectionKey = keyIterator.next();
                if (selectionKey.isAcceptable()) {
                    // 该客户端生成一个socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    // 将socketChannel注册到selector,并关联一个buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("客户端连接后，注册的SelectionKey，数量=" + selector.keys().size());

                    System.out.println("客户端连接成功，生成socketChannel：" + socketChannel.hashCode());
                }
                if (selectionKey.isReadable()) {
                     // 通过key反向获取channel
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                    socketChannel.read(buffer);
                    System.out.println("服务端接收到客户端数据："+ new String(buffer.array()));
                }

                // 手动从集合中当前的selectKey，防止重复
                keyIterator.remove();

            }
        }
    }
}
